package com.ganbo.thread.producer_consumer.single.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by gan on 2020/5/20 23:38.
 */
public class ProducerAndConsumerMode {

    private static Long value;
    private static Lock lock = new ReentrantLock();

    private static Condition conditionA = lock.newCondition();
    private static Condition conditionB = lock.newCondition();


    public static void producer() throws InterruptedException {
        while (true) {
            lock.lock();
            if (value == null) {
                value = System.currentTimeMillis();
                System.out.println(Thread.currentThread().getName() + "生产者生产的值为：" + value);
                conditionB.signal();
                conditionA.await();
            }
            lock.unlock();
        }
    }


    public static void consumer() throws InterruptedException {
        while (true) {
            lock.lock();
            if (value != null) {
                System.out.println(Thread.currentThread().getName() + "消费者消费的值为：" + value);
                value = null;
                conditionA.signal();
                conditionB.await();
            }
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        final ProducerAndConsumerMode mode = new ProducerAndConsumerMode();

        new Thread(new Runnable() {
            public void run() {
                try {
                    mode.producer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                try {
                    mode.consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

}
